package com.jeomo.masterdata.starter.service.impl;

import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.core.exception.BusinessException;
import com.jeomo.common.util.RedisUtil;
import com.jeomo.masterdata.starter.constant.MemberRedisKey;
import com.jeomo.masterdata.starter.entity.Level;
import com.jeomo.masterdata.starter.mapper.LevelMapper;
import com.jeomo.masterdata.starter.service.ILevelService;
import com.jeomo.shiro.util.LoginSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <h3>jeomo</h3>
 * <p>等级</p>
 *
 * @author : 崔贺
 * @date : 2020-09-01 16:00
 **/
@Transactional(rollbackFor = Exception.class)
@Service
public class LevelServiceImpl extends BaseServiceImpl<LevelMapper, Level> implements ILevelService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String CACHE_KEY = MemberRedisKey.MEM_LEVEL_HASH_KEY;

    @Resource
    private LevelMapper levelMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public int create(Level level) {
        String currentOrgCode = LoginSessionUtil.getCurrentLoginInfo().getCurrentOrgCode();
        level.setCode(level.getLevelCode() + currentOrgCode);
        level.setOrgCode(currentOrgCode);
        level.setTopOrgCode(LoginSessionUtil.getCurrentLoginInfo().getTopOrgCode());
        if (level.getUpLevelDailyAmount() > level.getUpLevelSumAmount()) {
            throw new BusinessException("升级规则的单日累计消费金额必须小于等于总累计消费金额!");
        }
        int insert = levelMapper.insert(level);
        redisUtil.hset(CACHE_KEY, level.getCode(), level.getName());
        return insert;
    }

    @Override
    public Map<String, String> queryCache() {

        Map<Object, Object> cacheMap = redisUtil.hmget(CACHE_KEY);
        if (!cacheMap.isEmpty()) {
            return patchData(cacheMap);
        }
        refreshCache();
        cacheMap = redisUtil.hmget(CACHE_KEY);
        return patchData(cacheMap);
    }

    public Map<String, String> patchData(Map<Object, Object> cacheMap) {
        HashMap<String, String> levelMap = new HashMap<>(8);
        Set<Object> objects = cacheMap.keySet();
        for (Object object : objects) {
            levelMap.put(object.toString(), cacheMap.get(object).toString());
        }
        return levelMap;
    }

    /**
     * 刷新缓存:删除缓存key,读取数据库,加入缓存
     */
    @Override
    public void refreshCache() {
        redisUtil.del(CACHE_KEY);
        List<Level> levels = levelMapper.getAllLevels();
        for (Level level : levels) {
            redisUtil.hset(CACHE_KEY, level.getCode(), level.getName());
        }
    }

    /**
     * @description: allLevel(不包括停用的)和allLevelList区别在于是否加入停用，
     * 因为allLevel已经被前端页面调用，不好再改，只能新增allLevelList
     * @return: java.util.List<com.jeomo.masterdata.starter.entity.Level>
     * @author: 崔贺
     * @time: 2020/12/25 15:47
     */
    @Override
    public List<Level> allLevel() {
        return levelMapper.getAllLevel(LoginSessionUtil.getCurrentLoginInfo().getCurrentOrgCode());
    }

    @Override
    public List<Level> allLevelList() {
        String orgCode = LoginSessionUtil.getCurrentLoginInfo().getCurrentOrgCode();
        return levelMapper.getAllLevelList(orgCode);
    }

    @PostConstruct
    public void init() {
        logger.info("Redis缓存初始化:[会员等级]");
        refreshCache();
    }

}
